/**
 * Created by Weizehua on 2017/1/20.
 */
import {Component, Input} from "@angular/core";
import {NavController} from "ionic-angular";
import {RegisterRequest} from "./RegisterRequest";
import {FormBuilder, FormGroup, Validators, FormControl} from "@angular/forms";
import {Hash} from "../../Utils/Hash";
import {tr} from "../../Utils/Translator";

declare let initGeetest: any;

@Component({
    selector: "tc-register",
    templateUrl: "Register.html",
    providers: [RegisterRequest, Hash]
})
export class RegisterPage {
    captchaInfo: any;

    formGroup: FormGroup;
    @Input()
    formErrorMessages: string[] = [];
    @Input()
    sendCaptchaTick = 0;
    @Input()
    validStatus = {
        phone: false,
        sendCaptcha: true,
        captcha: false,
        password: false,
        password2: false,
    };

    formalValidationMessages = {
        phone: {required: tr("请输入手机号码"), pattern: tr("手机号只能是11位数字")},
        captcha: {required: tr("请输入验证码"), pattern: tr("验证码格式不正确")},
        password: {required: tr("请输入密码"), pattern: tr("密码的长度必须在8-20位之间")},
        password2: {required: tr("请输入确认密码"), pattern: tr("密码的长度必须在8-20位之间")},
    };

    constructor(private registerRequest: RegisterRequest,
                private navCtrl: NavController,
                private fromBuilder: FormBuilder,
                private hasher: Hash) {
        this.formGroup = fromBuilder.group(
            {
                phone: ['18807734862', Validators.pattern(/^\d{11}$/), c => this.phoneValidator(c)],
                captcha: ['123456', Validators.pattern(/^\d{4,8}$/), c => this.captchaValidator(c)],
                password: ['12345678', [Validators.pattern(/^(\d|\w){8,20}$/)],],
                password2: ['12345678', [c => this.password2Validator(c)]],
            }
        );
        this.formGroup.valueChanges.subscribe(data => this.onValueChanged(data));
        this.formGroup.statusChanges.subscribe(data => this.onValueChanged(data));

        this.sendCaptchaTimer();
        window['formGroup'] = this.formGroup;
        window['page'] = this;
        window['_phone'] = this.formGroup.controls.phone;
        window['_captcha'] = this.formGroup.controls.captcha;
    }

    sendCaptchaTimer() {
        if (this.sendCaptchaTick === 1 || this.sendCaptchaTick === 0) {
            this.validStatus.sendCaptcha = true;
            this.sendCaptchaTick = 0;
        }
        else {
            this.sendCaptchaTick--;
            this.validStatus.sendCaptcha = false;
        }
        setTimeout(() => this.sendCaptchaTimer(), 1000);
    }

    async phoneValidator(control: FormControl) {
        let res = await this.registerRequest.isPhoneRegistered(control.value);
        if (res) {
            return {
                [tr(`该手机号码已经注册`)]: true
            };
        }
    }

    async captchaValidator(control: FormControl) {
        if (!this.captchaInfo)
            return {[tr("请点击\"获取验证码\"")]: true};
        if (Number(new Date()) > Number(new Date(this.captchaInfo.expiredTime)))
            return {[tr("验证码已过期")]: true};
        if (!await this.hasher.captchaTest(
                control.value,
                this.formGroup.controls.phone.value,
                new Date(this.captchaInfo.expiredTime), this.captchaInfo.captchaDigest))
            return {
                [tr('验证码不正确！')]: true
            };
    }

    password2Validator(control: FormControl) {
        if (!this.formGroup)
            return;
        if (control.value !== this.formGroup.value.password)
            return {
                [tr('确认密码与密码不相符！')]: true
            }

    }

    onValueChanged(data?: any) {
        this.formErrorMessages = [];
        for (let controlName in this.formGroup.controls) {
            let msgHolder = this.formalValidationMessages[controlName];
            let control = this.formGroup.controls[controlName];
            if (control.dirty || control.touched) {
                if (control.errors) {
                    for (let errorName in control.errors) {
                        if (msgHolder && msgHolder[errorName]) {
                            this.formErrorMessages.push(`${msgHolder[errorName]}  `);
                        }
                        else
                            this.formErrorMessages.push(`${errorName}  `);
                    }
                    this.validStatus[controlName] = false;
                }
                else {
                    this.validStatus[controlName] = true;
                }
            }
        }
    }

    async onGetCaptchaClicked() {
        this.captchaInfo = await this.registerRequest.getCaptcha(this.formGroup.value.phone);
        this.sendCaptchaTick = 60;
    }

    async onRegisterClicked() {
        await this.registerRequest.register(
            this.formGroup.value.phone,
            this.formGroup.value.password,
            this.formGroup.value.captcha,
            this.captchaInfo);
    }
}
